package rpc.factory;

import lombok.NoArgsConstructor;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName: SingletonFactory
 * @Description: 用于获取单例模式的工厂类
 * @author: Kowk
 * @since:1.0.0
 */
@NoArgsConstructor
public class SingletonFactory {
    private static final Map<String,Object> OBJECT_MAP = new ConcurrentHashMap<>();

    public static <T> T getInstance(Class<T> clazz){
        if (clazz == null) {
            throw new IllegalArgumentException();
        }
        String key = clazz.toString();
        if(OBJECT_MAP.containsKey(key)){
            return clazz.cast(OBJECT_MAP.get(key));
        } else {
            return clazz.cast(OBJECT_MAP.computeIfAbsent(key,k -> {
                try {
                    return clazz.getDeclaredConstructor().newInstance();
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e.getMessage(),e);
                } catch (InstantiationException e) {
                    throw new RuntimeException(e.getMessage(),e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e.getMessage(),e);
                } catch (NoSuchMethodException e) {
                    throw new RuntimeException(e.getMessage(),e);
                }
            }));
        }
    }

}
